<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\File\Http\Controller\Api;

use App\Exception\BusinessException;
use App\Http\Admin\Controller\AbstractController as AdminAbstractController;
use App\Http\Admin\Request\UploadRequest;
use App\Http\Common\Middleware\AccessTokenMiddleware;
use App\Http\Common\Result;
use App\Http\Common\ResultCode;
use App\Http\CurrentUser;
use App\Service\AttachmentService;
use Hyperf\Collection\Arr;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Request;
use Hyperf\Support\Filesystem\Filesystem;
use Hyperf\Swagger\Annotation\Delete;
use Hyperf\Swagger\Annotation\HyperfServer;
use Hyperf\Swagger\Annotation\Post;
use Mine\Swagger\Attributes\ResultResponse;
use Plugin\File\Service\RdFileVoiceService;
use Symfony\Component\Finder\SplFileInfo;

/**
 * 音频控制器
 * Class RdFileVoiceController
 */
#[HyperfServer(name: 'http')]
#[Middleware(middleware: AccessTokenMiddleware::class, priority: 100)]
final class RdFileUploadApiController extends AdminAbstractController
{

    /**
     * 业务处理服务
     * RdFileVoiceService
     */
    public function __construct(
        protected readonly RdFileVoiceService $service,
        protected readonly CurrentUser        $currentUser,
        protected readonly AttachmentService  $attachmentService,
        protected readonly Filesystem         $fileSystem
    )
    {
    }


    #[Post(
        path: '/file/api/rdFileUpload',
        summary: '上传附件',
        security: [['Bearer' => [], 'ApiKey' => []]],
    )]
    #[ResultResponse(instance: new Result())]
    public function upload(UploadRequest $request): Result
    {
        $uploadFile = $request->file('file');
        $newTmpPath = sys_get_temp_dir() . '/' . uniqid() . '.' . $uploadFile->getExtension();
        $uploadFile->moveTo($newTmpPath);
        $splFileInfo = new SplFileInfo($newTmpPath, '', '');
        return $this->success(
            $this->attachmentService->upload($splFileInfo, $uploadFile, $this->currentUser->id())
        );
    }

    #[Delete(
        path: '/file/api/rdFileDelete',
        summary: '删除附件',
        security: [['Bearer' => [], 'ApiKey' => []]],
    )]
    #[ResultResponse(instance: new Result())]
    public function delete(Request $request): Result
    {
        $params = $request->all();
        if (! ($id = Arr::get($params, 'id'))) {
            $url = Arr::get($params, 'url');
            if (! $url) {
                throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, '参数错误');
            }
            $id = $this->attachmentService->getRepository()->getQuery()
                ->whereIn('url', Arr::wrap($url))
                ->pluck('id')->toArray();
        }
        $fileInfo = $this->attachmentService->getRepository()->getQuery()
            ->where('created_by', $this->currentUser->id())
            ->whereIn('id', Arr::wrap($id))
            ->pluck('url')->toArray();
        if (!$fileInfo) {
            throw new BusinessException(ResultCode::FORBIDDEN, '没有操作权限');
        }
        foreach ($fileInfo as $url) {
            $filePath = BASE_PATH . '/storage/' . $url;
            $this->fileSystem->delete($filePath);
            $this->attachmentService->deleteById($id);
        }
        return $this->success();
    }
}